
import http from '@/http'
import $ from 'jquery'
let Utility = {
  removeSuffix: (str) => {
    if (!str.includes('.')) {
      return str
    }
    return str.substring(0, str.lastIndexOf('.'))
  },
  getAxioCommonBody: () => {
    let token = sessionStorage.getItem('token'),
    tokenType = 'SSO-AUTH'
    return {
      bizContent: '',
      loginAuthInfo: {
        isEnt: '',
        loginToken: token,
        loginTokenType: tokenType,
        operatorId: '',
        operatorName: '',
        partnerId: '',
        institution: 'wechat',
        bizType: 'fps',
      },
      requestNo: `requestno${new Date().getTime()}${parseInt(
        Math.random() * 1000000
      )}`,
      sarsTokenId: window.blackbox ? window.blackbox : '',
      service: '',
      sign: '1245',
      signType: 'AES',
      terminalInfo: {
        terminal: 'WEB',
      },
      timestamp: new Date().getTime(),
      version: '1.0.0',
    }
  },
  uploadFileV2: (paraFile, supplementFilename = '') => {
    let form = new FormData()
    let _gateway = Utility.getAxioCommonBody()
    let _fileName =
      new Date().getTime() + '_' + Utility.removeSuffix(paraFile.name)
    if (supplementFilename) _fileName += `_${supplementFilename}`
    form.append('fileName', _fileName)
    form.append('file', paraFile, paraFile.name)
    form.append('bizType', 'kyb')
    form.append('sysCode', 'cb_trade')
    form.append('requestBaseStr', JSON.stringify(_gateway))
    // 文件上传
    return http.post({
      baseURL: 'https://api-gateway.kjtpay.com/api-gateway',
      url: '/uploadFileV2', // TODO
      headers: { 'X-Requested-With': 'XMLHttpRequest' },
      method: 'post',
      data: form,
    })
  },
  downloadFile: (fileurl, filename) => {
    let a = document.createElement("a");
    a.download = filename; // 下载后文件名
    a.style.display = "none";
    $.ajax({
      url: fileurl,
      xhrFields: { responseType: "arraybuffer" },
    }).done(result => {
      let blob = new Blob([result]); // 字符内容转变成blob地址 二进制地址
      a.href = URL.createObjectURL(blob);
      document.body.appendChild(a);
      a.click(); // 触发点击
      document.body.removeChild(a); // 然后移除
    });
  },
}
export default Utility
